import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import Left from '@/pages/dnd/left/Left';
import Right from '@/pages/dnd/right/Right';
import { useState } from 'react';

function findItem(data: Item, id: number): Item {
  let res: Item;

  function test(list: Item[] = []) {
    list.forEach((item) => {
      if (item.id === id) {
        res = item;
      } else {
        test(item.items);
      }
    });
  }

  if (data.id === id) {
    res = data;
  } else {
    test(data.items);
  }
  return res;
}

export interface Item {
  id: number;
  type: string;
  items?: Item[];
  parentId: number;
}

const root: Item = {
  id: 1,
  type: 'Page',
  parentId: 0,
  items: [
    // {id: 2, parentId: 1, type: 'Button'},
    // {id: 3, parentId: 1, type: 'Button'},
    // {id: 4, parentId: 1, type: 'View'},
  ],
};

export default function Page() {
  const [data, setData] = useState<Item>(root);

  function handleAddCard(target: any, d: Item) {
    console.log(target);
    console.log(d);
    const item = findItem(data, target.id);

    const obj: Item = {
      id: Math.ceil(Math.random() * 10000),
      type: d.type,
      parentId: 0,
    };
    if (d.type === 'View') {
      obj.items = [];
    }
    if (item.items && target.insert) {
      obj.parentId = item.id;
      item.items.push(obj);
    } else {
      obj.parentId = item.parentId;
      const parent = findItem(data, item.parentId);
      const index = parent.items?.findIndex((child) => child.id === item.id)!;
      parent.items?.splice(index, 0, obj);
    }
    setData({ ...data });
  }

  function handleMove(target1: any, data1: any) {
    console.log(target1);
    const { dragItem, overItem, insert } = target1;
    if (!dragItem) {
      return;
    }
    const { draggedId, dragParentId } = dragItem;
    const { overId, overParentId } = overItem;
    const item = { ...findItem(data, draggedId) };
    if (insert) {
      const target = findItem(data, overId);
      item.parentId = target.id;
      removeNode(draggedId, dragParentId);
      target.items?.push(item);
    } else {
      const target = findItem(data, overParentId);
      const index = target.items?.findIndex((v) => v.id === overId)!;
      item.parentId = target.id;
      removeNode(draggedId, dragParentId);
      target.items?.splice(index, 0, item);
    }
    setData({ ...data });
  }

  function removeNode(removeId: number, parentId: number) {
    const item = findItem(data, parentId);
    const index = item.items?.findIndex((child) => child.id === removeId)!;
    item.items?.splice(index, 1);
  }

  return (
    <DndProvider backend={HTML5Backend}>
      <div style={{ display: 'flex' }}>
        <div style={{ width: 100 }}>
          <Left onEndDrag={handleAddCard} />
        </div>
        <div style={{ flex: 1 }}>
          <Right data={data} move={handleMove} />
        </div>
      </div>
    </DndProvider>
  );
}
